package com.ycx.furns.web;

import com.ycx.furns.entity.Cart;
import com.ycx.furns.entity.Member;
import com.ycx.furns.entity.Order;
import com.ycx.furns.entity.OrderItem;
import com.ycx.furns.service.OrderService;
import com.ycx.furns.service.impl.OrderServiceImpl;
import com.ycx.furns.utils.JDBCUtilsByDruid;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;

@WebServlet("/orderServlet")
public class OrderServlet extends BasicServlet{
    OrderService orderService = new OrderServiceImpl();
    protected void saveOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cart cart = (Cart)req.getSession().getAttribute("cart");
        Member member = (Member)req.getSession().getAttribute("member");
        String orderId = "";
        if(!(cart == null || cart.isEmpty())){
//            try {
//                orderId = orderService.saveOrder(cart, member.getId());
//                JDBCUtilsByDruid.commit();
//            } catch (Exception e) {
//                JDBCUtilsByDruid.rollback();
//                throw new RuntimeException(e);
//            }
            orderId = orderService.saveOrder(cart, member.getId());
            cart.clear();
        }
        req.getSession().setAttribute("orderId", orderId);
        resp.sendRedirect(req.getContextPath() + "/views/member/checkout.jsp?orderId=" + orderId);
    }

    protected void manageOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Member member = (Member)req.getSession().getAttribute("member");

        List<Order> orders = orderService.queryOrders(member.getId());
        req.setAttribute("orders", orders);
        req.getRequestDispatcher("/views/member/order.jsp").forward(req, resp);
    }

    protected void orderDetail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String orderId = req.getParameter("orderId");
        List<OrderItem> orderItems = orderService.queryOrderItems(orderId);
        int totalCount = 0;
        BigDecimal totalPrice = new BigDecimal(0);
        for (OrderItem orderItem : orderItems) {
            totalCount += orderItem.getCount();
            totalPrice = orderItem.getTotalPrice().add(orderItem.getTotalPrice());
        }
        req.setAttribute("orderItems", orderItems);
        req.setAttribute("totalCount", totalCount);
        req.setAttribute("totalPrice", totalPrice);
        req.getRequestDispatcher("/views/member/order_detail.jsp").forward(req, resp);
    }
}
